'use strict';
const Path = require("path"), fs = require('fs');

module.exports = (request, response, rfun)=>{
    //读取本地文件
	let path = request.GET.pathname;
	path = Path.normalize(path).replace(/\.\./g, "");
	path = Path.normalize(path);
	path = request.SITE["root"] + path;
    fs.stat(path, onStat);
	
	function onStat(err, stats){
		if(err && err.code == 'ENOENT'){
			if(rfun) rfun();
			else if(request.SITE.proxy){
				//console.log(request.GET.pathname);
				request.headers.host = request.SITE.proxy.host;
				let runMod = require(request.SITE.proxy.mod);
				runMod(request,response,rfun);
			}else{
                response.statusCode = 404;
				response.end("not find file");
            }
		}else{
			if(stats.isDirectory()){
				path += "/index.html";
				fs.stat(path, onStat);
			}else{
				if(request.headers['if-modified-since'] == stats.mtime.toUTCString()){
					response.statusCode = 304;
					response.end();
				}else{
					response.setHeader("last-modified", stats.mtime.toUTCString());
					let stream = fs.createReadStream(path);
					stream.pipe(response);				
				}
			}
		}
	}
}